package baseFx.common.context.spring;

import baseFx.common.Action1T;
import baseFx.common.utils.ClassUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.TypeConverter;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;

import java.util.Set;

public class SpringBeanFactory extends DefaultListableBeanFactory {
    Action1T<AutowiredBeforeEventArgs> onAutowiredBefore;

    @Override
    public Object resolveDependency(DependencyDescriptor descriptor, String requestingBeanName, Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {
        if (onAutowiredBefore == null) {
            return super.resolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
        }
        BeanDefinition def = getBeanDefinition(requestingBeanName);
        Class<?> clazz = ClassUtils.getClassForName(def.getBeanClassName());
        AutowiredBeforeEventArgs args = new AutowiredBeforeEventArgs(requestingBeanName, clazz, descriptor.getField());
        onAutowiredBefore.execute(args);
        if (args.result == null) {
            args.result = super.resolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
        }
        return args.result;
    }
}
